<?php


namespace app\command;


use app\services\cupboard\CupboardService;
use app\services\cupboard\FranchiserService;
use app\services\delivery\DeliveryGroupService;
use app\services\delivery\DeliveryService;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class CheckGroupOrder extends Command
{
    protected function configure()
    {
        $this->setName('check_group_order')->setDescription('配货订单检测');
    }

    protected function execute(Input $input, Output $output)
    {
        $time = date('Y-m-d H:i:s', strtotime("-2 days"));
        $list = Db::name('delivery_order')
            ->where('status', 0)
            ->where('create_time', '<', $time)
            ->select()
            ->toArray();
        if (!$list) {
            return $output->writeln('没有可执行的数据！');
        }
        foreach ($list as $value) {
            $cupboardInfo = CupboardService::getCupboardInfo($value['cupboard_id']);
            $franchiserInfo = FranchiserService::getFranchiserInfo($value['franchiser_id']);
            $data = [
                'status' => 2,
                'franchiser_phone' => $franchiserInfo['phone'],
                'franchiser_name' => $franchiserInfo['name'],
                'cupboard_name' => $cupboardInfo['name'],
                'lng' => $cupboardInfo['lng'],
                'lat' => $cupboardInfo['lat'],
                'address' => $cupboardInfo['address'],
                'over_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s')
            ];
            Db::name('delivery_order')->where('id', $value['id'])->update($data);
            // 更新组是否完成
            $count = DeliveryService::getCompleteOrderInfo($value['group_no']);
            if ($count == 0) {
                DeliveryGroupService::updateData($value['group_no'], [
                    'status' => 1
                ]);
            }
        }
        return $output->writeln('执行完毕！');
    }
}